﻿
using LYR_RPA.models.entity;
using LYR_RPA.models.enums;
using LYR_RPA.models.project;
using LYR_RPA.Properties;
using LYR_RPA.service;
using LYR_RPA.utils;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;

namespace LYR_RPA.models.events
{
    public class MessageHandle
    {
        private readonly WebSocketClient WebSocketClient;
        public MessageHandle() {
            WebSocketClient = WebSocketClient.Instance;
            WebSocketClient.MessageReceived += SocketService_MessageReceived;
        }

        private async void SocketService_MessageReceived(object sender, Result<object> e)
        {
            Project data ;
            Console.WriteLine($"{JSONUtils.ObjectToString(e)}");
            string json="";
            switch (e.Code)
            {
                case 10002://获取脚本列表
                    json = JSONUtils.ObjectToString(Result<ObservableCollection<Project>>.ResultContent(ResultEnum.PROJECT, CommonUtils.ReadProject()));
                    WebSocketClient.SendMessage(json);
                    break;
                case 10003:
                    //执行脚本
                     data=JSONUtils.StringToObject<Project>(JSONUtils.ObjectToString(e.Data));

                    foreach (var item in CommonUtils.ProjectCollections)
                    {
                        if (item.Path.Equals(data.Path))
                        {
                            var execute = new Execute()
                            {
                                Name = data.ScriptName,
                                Path = data.Path,
                                IsCommand = true,
                                Msg = "正在等待执行",
                                IsExecute = false,
                                State = "Orange",
                                CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            };
                            await Task.Run(() =>
                            {
                                CommonUtils.AddExecuteTask(execute);
                            });
                           
                            break;
                        }
                    }
                    break;
                case 10004:
                    //取消脚本
                    data = JSONUtils.StringToObject<Project>(JSONUtils.ObjectToString(e.Data));
                    for(int i = 0; i < CommonUtils.ExecuteCollections.Count; i++)
                    {
                        var item = CommonUtils.ExecuteCollections[i];
                        if (item.Path.Equals(data.Path))
                        {
                            if (item.Processing != null && !item.Processing.HasExited)
                            {
                                var project = new Project() { Path = item.Path, ScriptName = item.Name, UpdateTime = item.CreateTime };
                                WebSocketClient.SendMessage(JSONUtils.ObjectToString(Result<object>.ResultContent(ResultEnum.CANCEL_CANCEL_TRUE, project)));
                                WebSocketClient.SendMessage(JSONUtils.ObjectToString(Result<object>.ResultContent(ResultEnum.EXECUTE_SUCCESS, project)));
                                CommonUtils.CloseProcess("UiPath.Executor");
                                item.IsExecute = false;
                                WebSocketClient.SendMessage(JSONUtils.ObjectToString(Result<object>.ResultContent(ResultEnum.EXECUTE_FAIL, project)));
                                var execute = new Execute()
                                {
                                    Name = data.ScriptName,
                                    Path = data.Path,
                                    IsCommand = true,
                                    Msg = "取消执行",
                                    IsExecute = false,
                                    State = "Orange",
                                    CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                };
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    if (CommonUtils.LogCollections.Count > 0)
                                    {
                                        CommonUtils.LogCollections.Insert(0, execute);
                                    }
                                    else
                                    {
                                        CommonUtils.LogCollections.Add(execute);
                                    }
                                });
                            }
                            else
                            {
                                WebSocketClient.SendMessage(JSONUtils.ObjectToString(Result<object>.ResultContent(ResultEnum.EXECUTE_SUCCESS, null)));
                            }
                            break;
                        }
                    }
                    break;
                case 10011:

                    string command=e.Data.ToString();
                    Process p = new Process();
                    p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                    p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
                    p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
                    p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
                    p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
                    p.StartInfo.CreateNoWindow = true; //不显示程序窗口
                    p.Start();//启动程序

                    //向cmd窗口写入命令
                    p.StandardInput.WriteLine(command.Trim().TrimEnd('&') + "&exit");
                    p.StandardInput.AutoFlush = true;

                    //获取cmd窗口的输出信息
                    string output = p.StandardOutput.ReadToEnd();
                    Console.WriteLine(command);
                    Console.WriteLine(output);
                    json = JSONUtils.ObjectToString(Result<string>.ResultContent(ResultEnum.EXECUTE_COMMAND, output));
                    WebSocketClient.SendMessage(json);
                    Console.WriteLine(json);
                    p.WaitForExit();//等待程序执行完退出进程
                    p.Close();
                    break;
                case 10012:
                    Settings.Default.ID= e.Data.ToString().Trim();
                    Settings.Default.Save();
                    break;
            }
        }
    }
}
